package com.xaicode.learn.netty.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 23:41
 */
public class NettyClient {

    public static void main(String[] args) {

        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // create client bootstrap
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                    // thread pool group
                    .group(workerGroup)
                    // client channel
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            final ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new NettyClientHandler());
                        }
                    });

            // connect and start
            final ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();

            // listen closed channel
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // shutdown
            workerGroup.shutdownGracefully();
        }

    }

}
